import { withLoading } from 'utils/dva';
import services from '../../services';
import model from '../model';
import { pageConfig } from 'configs/constants';

const defaultConfig = {
  pagination: {
    ...pageConfig,
    total: 0
  },
  list: []
};


export default model.extend ({

  namespace: 'articleList',

  state: {
    config: defaultConfig,
    user: [],
    category: [],
    loading: {
      list: false,
      add: false,
      del: false
    }
  },

  subscriptions: {
    setup({ dispatch, history }) {
      // 监听路由的变化，请求页面数据
      return history.listen(({ pathname }) => {
        let list = [];
        if (pathname === '/article/list') {
          dispatch({ type: 'getList', payload: { list } });
        }
      });
    }
  },

  effects: {
    * getList({ payload }, { call, select, update }) {
      const { config: { pagination } } = yield select(({ articleList }) => articleList);
      const { pageSize, current } = pagination;
      const { data } = yield call(withLoading(services.article.getArticleList, 'list'), 
      { ps: pageSize, pn: current, ...payload });
      yield update({ 
        config: {
          list: data.list,
          pagination: {
            ...pagination,
            total: data.total
          }
        }
       });
    },
    * getListAll({ payload }, {call, update}){
      const { data } = yield call(withLoading(services.user.getCategoryAll), payload);
      yield update({ category: data.data });
    },
    * del({ payload }, {call, put}){
      yield call(withLoading(services.article.delArticle), payload);
      yield put({ type: 'getList' });
    }
  },

  reducers: {
    goPage(state, { payload }) {
      return {
        ...state,
        config: {
          ...state.config,
          pagination: {
            ...state.config.pagination,
            current: payload
          }
        }
      };
    }
  }

});
